package com.xiyue.server.config;


import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Hidden
@Configuration
public class SaTokenConfiguration implements WebMvcConfigurer {
    //http://localhost:8080/v3/api-docs
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册SaToken拦截器
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 指定match规则
            SaRouter
                    .match("/**")
                    .notMatch("/favicon.ico","/doc.html",
                            "/webjars/**","/v3/api-docs/**",
                            "/.well-known/**")
                    .check(r -> StpUtil.isLogin());
        }))
                .addPathPatterns("/**")
                .excludePathPatterns("/error");
    }

    @Bean
    public SaServletFilter saServletFilter(){
        return new SaServletFilter()
                .setBeforeAuth(obj -> {
                    SaHolder.getResponse()
                            // 设置跨域响应头
                            // 允许制定域访问间跨域资源
                            .setHeader("Access-Control-Allow-Origin", "*")
                            .setHeader("Access-Control-Allow-Methods", "*")
                            .setHeader("Access-Control-Allow-Headers", "*")
                            .setHeader("Access-Control-Max-Age", "3600");
                    // 如果是预检请求，则立即返回前端
                    SaRouter.match(SaHttpMethod.OPTIONS).back();
                });
    }
}
